<?php   namespace Admin\Controller;
class StuController extends CommonController {
    //学生管理首页
    private static $cid;
    public function __construct()
    {
        parent::__construct();
        self::$cid = $_GET['cid'];
        $this->assign("cid",self::$cid);
    }

    public function index(){
        $cids = self::$cid;
//        p($cid);exit;
		$cid = (int)$_GET['cid'];
		$back = $this->check($cid);
		if($back['valid'] == 0){
			$localCid = $back['cid'];
			header("location:index.php?m=Admin&c=Stu&a=index&cid={$localCid}");
		}
        if (IS_POST){
            //提交的学生姓名
            $sname = $_POST['sname'];
            $age = $_POST['age'];
            $sex = $_POST['sex'];
//            p($_POST['sname']);
            //2.写入数据库
            M()->exec("insert into student(name,age,sex,cid) values('{$sname}',{$age},'{$sex}',{$cids})");
            $this->success("添加成功","index.php?m=Admin&c=Stu&cid={$cid}");
            exit;
        }
        $this->assign("title","学生管理首页");
        $data = M()->query("select * from student s join class c on s.cid=c.cid where s.cid={$cids}");
        $this->assign("data",$data);
        $this->display();
    }
//	修改
    public function edit(){
        $cids = self::$cid;
		$cid = (int)$_GET['cid'];
		$back = $this->check($cid);
		if($back['valid'] == 0){
			$localCid = $back['cid'];
			header("location:index.php?m=Admin&c=Stu&a=index&cid={$localCid}");
		}
        if (IS_POST){
            $sid = $_POST['sid'];
            $sname = $_POST['sname'];
            $sex = $_POST['sex'];
            $age = $_POST['age'];
            //执行修改
            M()->exec("update student set name='{$sname}',age={$age},sex='{$sex}' where sid={$sid}");
            $this->success("修改成功","index.php?m=Admin&c=Stu&cid={$cids}");
            exit;
        }
        $this->error("非法请求","index.php?m=Admin&c=Stu&cid={$cids}");
    }
//		删除
    public function del(){
        $cid = self::$cid;
        if(IS_POST){
            $sid = $_POST["sid"];
            M()->exec("delete from student where sid={$sid}");
            $this->success("删除成功","index.php?m=Admin&c=Stu&cid={$cid}");
            exit;
        }
        $this->error("非法请求","index.php?m=Admin&c=Stu&cid={$cid}");
    }
	public function check($cid){
		//非法参数判断
		//$cids = [1,3,4,5,5];
		$cids = M()->query("select cid from class");
		//重组数组定义的临时空数组，最终重组完成之后的数据压入$temp
		$temp = [];
		foreach ($cids as $key => $value) {
			$temp[]=$value['cid'];
		}
		if(!in_array($cid, $temp)){
			//错误提示
			//$this->error("非法操作","index.php?m=Admin");exit;
			//刷新当前页面
			//如果是非法参数，返回标识0
			$localCid=$temp[0];
			return['valid'=>0,'cid'=>$localCid];
		}
			return['valid'=>1,'cid'=>''];
	}
}
